#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-sysctl
# REQUIRE: ix-update
# BEFORE: ix-zfs

. /etc/rc.subr

set_autotune_sysctls()
{
	local IFS="
"
	local autotune

	export PATH=$PATH:/usr/local/bin:/usr/local/sbin

	autotune=/usr/local/bin/autotune
	if [ -x $autotune ]; then
		if [ "$(LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/midclt call system.is_freenas)" = "False" ]; then
			$autotune \
				-o \
				--kernel-reserved=6442450944 \
				--userland-reserved=4831838208 \
				--conf sysctl
		else
			$autotune \
				-o \
				--kernel-reserved=1073741824 \
				--userland-reserved=2417483648 \
				--conf sysctl
		fi

	fi
}

set_user_sysctls()
{
	local IFS="|"
	local f="tun_var tun_value"
	eval local $f
	local sf=$(var_to_sf $f)

	# Generate sysctls
	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
		"SELECT $sf FROM system_tunable WHERE tun_enabled = 1 AND tun_type = 'sysctl' ORDER BY id" | \
	while eval read -r $f; do
		sysctl ${tun_var}="${tun_value}"
	done
}

start_sysctl()
{
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
	set_autotune_sysctls
	set_user_sysctls
}

reload_sysctl()
{
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT
	set_user_sysctls
}

name="ix-sysctl"
start_cmd='start_sysctl'
reload_cmd='reload_sysctl'
stop_cmd=':'
extra_commands='reload'

load_rc_config $name
run_rc_command "$1"
